﻿using System;
using System.AddIn;
using System.Collections.Generic;
using System.Net;
using System.Windows;
using System.Windows.Forms;
using Bookvar.AddIns.AddInViews;
using Bookvar.Common;
using Bookvar.ObjectModel;
using Facebook.Desktop;
using Facebook.Service;

namespace Bookvar.AddIns.Facebook
{
    [AddIn( "Bookvar Facebook AddIn", Version = "1.0.0.0" )]
	public class FacebookAddin : EditableBookvarAddinView
	{
		public override Topic Execute( Topic topic )
		{
			FormHost host = new FormHost();
			Window window = new Window();
			window.Title = "Facebook Login";
			window.Width = 50;
			window.Height = 50;

			host.Child = new Form();

			window.Content = host;

			window.Show();

			FacebookClientSession session =
				new FacebookClientSession( "e144d11bd12756817a2962a2b5b77dc1", "bbc39bdc4dce083980034d345c0e5ff6" );
			if ( session.Initialize( host.Child ) )
			{
				FacebookService service = new FacebookService( session );

				topic = CreateTopicFromUser( service.Users.GetUser( service.UserID, null ) );

				ICollection<string> friendIDs = service.Friends.GetFriends( FriendFilter.AllFriends );
				ICollection<User> users = service.Users.GetUsers( friendIDs, null );
				if(users != null)
				{
					foreach ( User user in users )
					{
						Topic userTopic = CreateTopicFromUser( user );
						topic.SubTopics.Add( userTopic );
					}
				}
			}

			window.Close();

			//TODO: construct topic

			return topic;
		}

		private static Topic CreateTopicFromUser( User user )
		{
			Topic topic = new Topic();
			topic.Name = user.Name;
			topic.Hyperlink = new Uri( "http://www.facebook.com/profile.php?id=" + user.ID );

            Resource image = null;
		    var client = new WebClient();

			try
			{
				if ( !string.IsNullOrEmpty( user.PictureUrl ) )
				{
				    image = new Resource { ResourceType = ResourceType.Image };
                    image.ResourceBytes = client.DownloadData( user.PictureUrl );
				}
			}
			catch ( WebException )
			{
				image = null;
			}
			finally
			{
				client.Dispose();
			}
			if ( image != null && image.ItemSource != null )
			{
				topic.Resources.Add( image );
			}

			return topic;
		}


		public override AddinInfo Info
		{
			get
			{
				AddinInfo info = new AddinInfo();
				info.Name = "Facebook";
				info.Group = "Social";
				info.Description = "Look in new way of your facebook friends";
				info.Image = AssemblyUtility.LoadImageFromResources(
					typeof ( FacebookAddin ).Assembly, "Bookvar.AddIns.Facebook.Facebook.png" );

				return info;
			}
		}
	}
}
